﻿using MyX.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyX.Bus
{
    public interface XIMessageBus
    {
        string Topic { get; }
        void Send(XIMessage message);
        void Receive(XIMessage message);
    }

    public abstract class XMessageBus<T> : XIMessageBus where T : class, XIMessage
    {
        public XMessageBus(string topic, XIMQ mq)
        {
            Topic = topic;
            MQ = mq;
            MQ.Register(this);
        }

        public string Topic
        {
            get; protected set;
        }

        protected XIMQ MQ { get; private set; }

        public void Receive(XIMessage message)
        {
            var tMessage = message as T;
            if (tMessage == null)
                throw new Exception("不能处理该类型消息" + message.GetType());
            ReceiveCore(tMessage);
        }

        protected abstract void ReceiveCore(T message);

        public void Send(XIMessage message)
        {
            var tMessage = message as T;
            if (tMessage == null)
                throw new Exception("不能发送该类型消息" + message.GetType());            
            SendCore(tMessage);
            MQ.Send(Topic, tMessage);
        }

        protected abstract void SendCore(T message);

    }
}
